package com.leyou.goodsDetail.service;

import com.leyou.common.thread.ThreadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @author shkstart
 * @create 2020-05-05 13:24
 */
@Service
public class GoodsHtmlService {
    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private GoodsDetailService goodsDetailService;

    public void createHtml(Long id){
        PrintWriter printWriter = null;

        try {
            Map<String, Object> map = goodsDetailService.buildGoodsSetail(id);

            Context context = new Context();
            context.setVariables(map);

            printWriter = new PrintWriter("F:\\biyaozujian\\nginx-1.14.0\\html\\" + id + ".html");

            templateEngine.process("item",context,printWriter);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            if (printWriter != null) {
                printWriter.close();
            }
        }
    }


    /**
     * 新建线程处理页面静态化
     * @param spuId
     */
    public void asyncExcute(Long spuId) {
        ThreadUtils.execute(()->createHtml(spuId));
        /*ThreadUtils.execute(new Runnable() {
            @Override
            public void run() {
                createHtml(spuId);
            }
        });*/
    }

}
